package com.lihepeng.leecode.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 自选锁demo
 * cas 底层也是使用的自旋锁
 */
public class SpinLockDemo {
    private static AtomicReference<Thread> atomicReference = new AtomicReference<>();

    /**
     * 加锁
     */
    public static void mySpinLock() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+"\t is comming in ");
        while (!atomicReference.compareAndSet(null,thread)){
            //System.out.println(thread.getName()+"自选等待中");
        }
    }
    public  static  void unlock() {
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(thread.getName()+"\t is invokeed  ");
    }
    public static void main(String[] args) throws InterruptedException {
        new Thread(()->{
            mySpinLock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            unlock();
        },"t1").start();
        TimeUnit.SECONDS.sleep(2);
        new Thread(()->{
            mySpinLock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            unlock();
        },"t2").start();
    }
}
